﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;

public partial class Controls_RepliesControl : System.Web.UI.UserControl
{
    Dictionary<string, int> count = null;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Cache["Report"] == null)
        {
            count = new Dictionary<string, int>();
        }
        else
        {
            count = (Dictionary<string, int>)Cache["Report"];            
        }

        Twitter twitter = new Twitter();

        string sXml = twitter.GetPublicTimeline(Twitter.OutputFormatType.XML);

        XDocument loaded = XDocument.Parse(sXml);

        var allElements = from stat in loaded.Descendants("status")
                          select new
                          {
                              Text = stat.Element("text").Value,
                              ID = stat.Element("id").Value,
                          };
        double dID = 0;

        foreach (var stat in allElements)
        {
            if (dID == 0)
                dID = Convert.ToDouble(stat.ID);

            if (Cache["LastID"] != null)
            {
                double lastID = Convert.ToDouble(Cache["LastID"].ToString());
                if (dID <= lastID)
                    break;
            }
                            

            if (stat.Text.IndexOf('@') > -1)
            {
                try
                {
                    string sUsername = stat.Text.Substring(stat.Text.IndexOf('@'), stat.Text.IndexOf(' ') - stat.Text.IndexOf('@'));
                    try
                    {
                        int iValue = count[sUsername];
                        count[sUsername] = iValue + 1;
                    }
                    catch
                    {
                        count.Add(sUsername, 1);
                    }
                }
                catch { }
            }
        }

        Cache["Report"] = count;
        var rows = count.OrderByDescending(item => item.Value);
        var newrows = rows.Take(30);

        Cache["LastID"] = dID;
        GridView1.DataSource = newrows;
        GridView1.DataBind();

    }
}
